<template>
  <div>
  <el-dialog
    title="班组信息"
    :visible.sync="dialogVisible"
    :modal="true"
    :appendToBody="true"
    width="60%"
    v-dialog-drag
    :close-on-click-modal="false"
    top="5vh"
    @close="handleClose()"
    @open="handleOpen()"
  >
    <PartitionTitle title="基础信息"></PartitionTitle>
    <el-form :model="form" :rules="rules" ref="ruleForm" :disabled="mode == 'look'" label-width="120px">
      <el-form-item label="班组编码" prop="erpWorkGroup">
        <el-input type="text" v-model="form.erpWorkGroup" placeholder="请输入班组编码" disabled></el-input>
      </el-form-item>

      <el-form-item label="班组名称" prop="erpWorkGroupDesc">
        <el-input type="text" v-model="form.erpWorkGroupDesc" placeholder="请输入班组名称"></el-input>
      </el-form-item>

      <el-form-item label="所属工厂" prop="erpOrganizationName">
        <el-input type="text" v-model="form.erpOrganizationName" placeholder="请选择所属工厂" disabled></el-input>
      </el-form-item>

      <el-form-item label="所属车间" prop="workshopId">
        <el-select
          v-model="form.workshopId"
          placeholder="请选择所属车间"
          size="small"
          clearable
          @change="handleWorkshop"
        >
          <el-option
            v-for="item in workshopList"
            :key="item.workshopId"
            :label="item.workshopName"
            :value="item.workshopId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="所属产线" prop='lineIdList'>
        <el-select
          v-model="form.lineIdList"
          placeholder="请选择产线"
          size="small"
          clearable
          multiple
          value-key="lineId"
          @change="handleLine"
        >
          <el-option
            v-for="item in lineList"
            :key="item.lineId"
            :label="item.lineName"
            :value="item.lineId"
          >
          </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="负责人" prop="groupHeadRealnames">
        <el-input type="text" v-model="form.groupHeadRealnames" placeholder="请选择班组负责人" readonly>
          <el-button slot="append" icon="el-icon-search" @click="openUserDialog"></el-button>
        </el-input>
      </el-form-item>

      <el-form-item label="班次类型" prop="classesName">
        <el-input type="text" v-model="form.classesName" placeholder="请选择班次类型" readonly>
          <el-button slot="append" icon="el-icon-search" @click="classesDialog.visible = true"></el-button>
        </el-input>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" :loading="saveloading" @click="handleSubmit" v-if='mode != "look"'>确 定</el-button>
    </span>
  </el-dialog>

  <userList
    :visibles.sync="userDialog.visible"
    :multiple="true"
    :defaultValues="userDialog.defaulSelectUsers"
    :selectableCallBack="selectableUserCallBack"
    @closeDialog="closeUserDialog"
    ></userList>
  <classes-dialog :visibles.sync="classesDialog.visible" :multiple="false" @submitDialog="submitClasses"></classes-dialog>
  </div>
</template>
<script>
  import classesDialog from "./classesDialog";
  import {getErpGroup,addOrUpdateErpGroup,getUnSelectableUserByGroupId} from "@/api/team/group";
  import { mapState,mapActions} from "vuex";
export default {
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    row: {
      type: Object,
      default: null
    },
    mode: {
      type: String,
      default: ""
    }
  },
  data() {
    const validLine = (rule, value, callback) =>{
      if (!this.form.lineIdList?.length) {
        return callback(new Error('请选择所属产线'));
      }else{
        callback();
      }
    }
    return {
      form: {
        erpWorkGroup: null,
        erpWorkGroupDesc: null,
        erpOrganizationId: null,
        erpOrganizationCode: null,
        erpOrganizationName: null,
        classesName:"",
        classesId:null,
        groupUsers:[],
        groupHeadRealnames:null,
        groupHeadUsernames: null,
        workshopId:null,
        lineIdList:[],
        erpGroupLineDtos:[]
      },
      rules: {
        erpWorkGroupDesc: [
          { required: true, message: "请填写班组名称", trigger: "change" },
        ],
        workshopId: [
          { required: true, message: "请选择所属车间", trigger: "change" },
        ],
        lineIdList:[
          {required: true,validator:validLine, trigger: "change" },
        ],
        classesName: [
          { required: true, message: "请选择班次类型", trigger: "change" },
        ],
        groupHeadRealnames: [
          { required: true, message: "请选择负责人", trigger: "change" },
        ]
      },
      userDialog: {
        visible: false,
        defaulSelectUsers:[],
        key: null
      },
      classesDialog: {
        visible: false
      },
      multipleSelection:[],
      workshopList:[],
      lineList:[],
      selectableUserCallBack: (row) => {
        return !this.disabledUser.includes(row.username)
      },
      saveloading: false
    };
  },
  computed: {
    dialogVisible: {
      set(val) {
        this.$emit("update:visible", val)
      },
      get() {
        return this.visible
      }
    },
    ...mapState({
      allList:(state) => state.common.allList
    }),
  },
  created(){
    this.getAllData()
  },
  methods: {
    ...mapActions(["getAllData"]),
    handleClose() {
      this.saveloading = false
      this.resetFormData()
    },

    handleOpen() {
      getErpGroup(this.row.id)
      .then(res=>{
        if (res.code == 200 && res.data) {
          this.form = res.data;
          this.form.classesId = this.form?.classesDto?.id;
          this.form.classesName = this.form?.classesDto?.classesName;
          if(this.form?.factoryDeptCode){
            this.handleFactory(this.form.factoryDeptCode)
          }
          if(this.form?.workshopId){
            this.handleWorkshop(this.form.workshopId)
          }
          if(this.form?.erpGroupLineDtos?.length){
            // const lineIdList = this.form?.erpGroupLineDtos.map(ele => ele.lineId);
            // this.$set(this.form,"lineIdList",lineIdList)
            this.form.lineIdList = this.form?.erpGroupLineDtos.map(ele => ele.lineId);
          }else{
            this.form.lineIdList = [];
          }
        } else {
          this.resetFormData()
        }
      }).catch(() => {
        this.resetFormData()
      })
    },

    handleSubmit() {
      this.saveloading = true
      this.$refs.ruleForm
      .validate((flag) => {
        if (flag) {
          const parmas = {
            id:this.row.id,
            erpWorkGroupDesc: this.form.erpWorkGroupDesc,
            classesId:this.form.classesId,
            workshopId:this.form.workshopId,
            groupHeadUsernames:this.form.groupHeadUsernames,
            groupUsers:this.form.groupUsers?.length ? this.form.groupUsers.map(ele => {return {username:ele.username}}) : [],
            erpGroupLineDtos:this.form.lineIdList?.length ? this.form.lineIdList.map(ele => {return {lineId:ele}}) : []
          }
          addOrUpdateErpGroup(parmas).then(res => {
            if (res.code == 200) {
              this.msgSuccess("操作成功")
              this.$emit("submit-success")
              this.dialogVisible = false
            } else {
              this.msgError(res.msg || "操作失败")
            }
            this.saveloading = false
          }).catch(() => {
            this.msgError("操作失败")
            this.saveloading = false
          })
        } else {
          this.saveloading = false
        }
      })
    },

    //选择班次类型
    submitClasses(list){
      if(list?.length){
        this.form.classesId = list[0].id;
        this.form.classesName = list[0].classesName;
      }
    },

    //打开人员选择器
    openUserDialog() {
      this.userDialog.defaulSelectUsers = [];
      getUnSelectableUserByGroupId(this.form.id).then(res => {
        this.disabledUser = res.data
      })
      let groupHeadUserList = this.form?.groupHeadUsernames?.split(",") || [];
      let groupHeadNameList = this.form?.groupHeadRealnames?.split(",") || [];
      if(groupHeadUserList?.length){
        groupHeadUserList.forEach((item,index) => {
          this.userDialog.defaulSelectUsers.push({
            username:item,
            realname:groupHeadNameList[index]
          })
        })
      }
      this.userDialog.visible = true;
    },

    closeUserDialog(list){
      if(list?.length){
        this.form.groupHeadUsernames = list.map(item => item.username).join();
        this.form.groupHeadRealnames = list.map(item => item.realname).join();
      }
      else{
        this.form.groupHeadUsernames = null;
        this.form.groupHeadRealnames = null;
      }
    },

    // 移除班组成员
    removeUser(){
      if(!this.multipleSelection?.length){
        this.msgWarning('请先选择要移除的成员!');
        return;
      }
      this.multipleSelection = this.multipleSelection.map(ele => ele.userId);
      this.form.groupUsers = this.form.groupUsers.filter(item => !this.multipleSelection.includes(item.userId));
      this.multipleSelection = [];
    },

    handleSelectionChange(selection, row){
      this.multipleSelection = selection
    },

    //选择工厂,获取车间数据
    handleFactory(val){
      const factoryItem = this.allList.find(ele => ele.factoryDeptCode === val);
      this.workshopList = factoryItem?.workshopVos ? factoryItem?.workshopVos : [];
    },

    //选择车间,获取产线数据
    handleWorkshop(val){
      this.form.lineIdList = null;
      this.lineList = [];
      const workshopItemn = this.workshopList.find(ele => ele.workshopId === val);
      this.lineList = workshopItemn?.productionLineVos ? workshopItemn?.productionLineVos : [];
    },

    handleLine(val){
      this.form.lineIdList = val;
      this.$forceUpdate();
    },

    resetFormData() {
      this.$refs.ruleForm?.resetFields()
      this.form = {
        erpWorkGroup: null,
        erpWorkGroupDesc: null,
        erpOrganizationId: null,
        erpOrganizationCode: null,
        erpOrganizationName: null,
        classesName:"",
        classesId:null,
        groupUsers:[],
        groupHeadRealnames:null,
        groupHeadUsernames: null,
        workshopId:null,
        lineIdList:[],
        erpGroupLineDtos:[]
      };
    },
  },

  components:{
    classesDialog
  }
};
</script>
<style lang="scss" scoped>
.el-form {
  display: flex;
  justify-content: space-between;
  flex-flow: wrap;
  .el-form-item {
    width: 49%;
  }
  .el-date-editor.el-input,
  .el-select {
    width: 100%;
  }
}
.tool-bar{
  margin-bottom:20px
}
</style>
